<template>
  <div style="padding: 20px">
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="auto"
      status-icon
    >
      <el-form-item label="商品类别名称" prop="categoryName">
        <el-input v-model="formData.categoryName" :disabled="disabled"></el-input>
      </el-form-item>
      <el-form-item label="商品类别代码" prop="categoryCode">
        <el-input v-model="formData.categoryCode" :disabled="disabled"></el-input>
      </el-form-item>
      <el-form-item
        v-for="(attr, index) in formData.spuCategoryAttrList"
        :key="index"
      >
        <el-col :span="7">
          <el-form-item
            :label="`属性名称${index + 1}`"
            :prop="'spuCategoryAttrList.' + index + '.attrName'"
            :rules="{
              required: true,
              message: '请输入属性名称'
            }"
          >
            <el-input v-model="attr.attrName" :disabled="disabled"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="15">
          <el-form-item
            label="属性值"
            :prop="'spuCategoryAttrList.' + index + '.attrValueList'"
            :rules="{
              required: true,
              message: '请输入属性值'
            }"
          >
            <el-input
              v-model="attr.attrValueList"
              placeholder="多个值以逗号分隔"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2" v-show="!disabled">
          <el-button
            @click="removeAttr(index)"
            type="danger"
            style="margin-left: 10px"
            >删除</el-button
          >
        </el-col>
      </el-form-item>
      <el-form-item label=" " v-show="!disabled">
        <el-button @click="addAttr" style="width: 100%">+ 添加属性</el-button>
      </el-form-item>
      <el-form-item class="footer" v-show="!disabled">
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { addProductCategory, editProductCategory } from '@/api/shop/index'

interface RuleForm{
  categoryName: string;
  categoryCode: string;
  spuCategoryAttrList?: [{ attrName: string; attrValueList: string, spuCategoryAttrId?: number }];
  attrName?: string;
  attrValueList?: string;
}

const props = defineProps(["closeDrawer", "drawerType"])

const disabled = computed(() => {
  return props.drawerType === 'view'
})

const ruleFormRef = ref<FormInstance>();
const formData = ref<RuleForm>({
  categoryName: "",
  categoryCode: "",
});
const editId = ref(-1)

const rules = reactive<FormRules<RuleForm>>({
  categoryName: [{ required: true, message: "请输入类别名称" }],
  categoryCode: [{ required: true, message: "请输入类别代码" }],
});

const addAttr = () => {
   const item = { attrName: "", attrValueList: "" }
  if(formData.value.spuCategoryAttrList) {
   formData.value.spuCategoryAttrList.push(item);
  } else {
    formData.value.spuCategoryAttrList = [item]
  }
};

const removeAttr = (index: number) => {
  formData.value.spuCategoryAttrList?.splice(index, 1);
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const spuCategoryAttrList = formData.value.spuCategoryAttrList?.map(_ => {
        const itemAttr: any = {
          attrName: _.attrName,
          attrValueList: _.attrValueList.replace(/，/g, ",").split(',')
        }
        if(props.drawerType === 'edit') {
          itemAttr.spuCategoryAttrId = _.spuCategoryAttrId
        }
        return itemAttr
      })
      if(props.drawerType === 'edit') {
        editProductCategory({ ...formData.value, spuCategoryAttrList, spuCategoryId: editId.value })
          .then(() => {
            ElMessage.success("更新成功");
            props.closeDrawer()
          })
          .catch(() => {
            ElMessage.warning("更新失败");
          })
      } else {
        addProductCategory({ ...formData.value, spuCategoryAttrList })
          .then(() => {
            ElMessage.success("添加成功");
            props.closeDrawer()
          })
          .catch(() => {
            ElMessage.warning("添加失败");
          })
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const initForm = (editData: any) => {
  editId.value = editData.spuCategoryId
  formData.value.categoryName = editData.categoryName
  formData.value.categoryCode = editData.categoryCode
  formData.value.spuCategoryAttrList = editData.spuCategoryAttrList?.map((_: any) => ({
    attrName: _.attrName,
    attrValueList: _.attrValueList.join(','),
    spuCategoryAttrId: _.spuCategoryAttrId
  })) || []
}

defineExpose({
  initForm
})
</script>

<style lang="scss" scoped>
.footer {
  position: absolute;
  bottom: 0;
  height: 100px;
  width: 100%;
  ::v-deep(.el-form-item__content) {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
